/**
 * 下载网络图片
 */
export const downloadImage = (imageUrl) => {
	uni.getSetting({ //获取用户的当前设置
		success: res => {

			if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
				saveImageToPhotosAlbum(imageUrl)
			} else {
				uni.hideLoading()
				uni.authorize({ //重新发起获取授权
					scope: 'scope.writePhotosAlbum',
					success: () => {
						saveImageToPhotosAlbum(imageUrl)
					},
					fail: () => {
						uni.showToast({
							title: '请打开保存相册权限，再点击保存相册分享',
							icon: 'none',
							duration: 2000
						})
						let timer = setTimeout(() => {
							clearTimeout(timer)
							uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
								success: e => {}
							})
						}, 2000)
					}
				})
			}
		}
	})
}

export const saveImageToPhotosAlbum = (imageUrl) => {
	wx.downloadFile({
		url: imageUrl,
		success: res => {
			uni.hideLoading()
			
			if (res.statusCode === 200) {
				wx.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success(res) {
						wx.showToast({
							title: '保存图片成功！',
						})
					},
					fail(res) {
						wx.showToast({
							title: '保存图片失败！',
						})
					}
				})
			}
		},
		fail: err => {
			uni.hideLoading()
			console.log(err, 'err')
			if(err.errno==600002){
				wx.showToast({
					title: '微信未授权下载图片！',
				})
			}
		}
	})

}